package com.oscar.ehome;

import android.app.NotificationManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;

import android.view.KeyEvent;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.Toast;

import com.google.gson.Gson;
import com.igexin.sdk.PushManager;
import com.oscar.ehome.base.AppManager;
import com.oscar.ehome.base.NotifationReceiver;
import com.oscar.ehome.base.activity.BasesActivity;
import com.oscar.ehome.base.fragment.adapter.CustomFragmentPagerAdapter;
import com.oscar.ehome.base.fragment.adapter.NoPreloadViewPager;
import com.oscar.ehome.bean.loginbean.UserBean;
import com.oscar.ehome.presenter.BasePresenter;
import com.oscar.ehome.utils.basethem.TintManager;
import com.oscar.ehome.utils.system.SystemConfigFactory;
import com.oscar.ehome.utils.util.CommonUtils;
import com.oscar.ehome.view.messageview.MessageFragment;
import com.oscar.ehome.view.pageview.HdFragment;
import com.oscar.ehome.view.pageview.PageFragment;
import com.oscar.ehome.view.pageview.StudyFragment;
import com.oscar.ehome.view.setview.CheckUpdateManger;
import com.oscar.ehome.view.setview.SetFragment;
import com.oscar.ehome.view.teamview.TeamFragment;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends BasesActivity implements NoPreloadViewPager.OnPageChangeListener, CompoundButton.OnCheckedChangeListener,
        EasyPermissions.PermissionCallbacks {

    /**
     * fragment布局
     */
    @BindView(R.id.ehome_frg)
    NoPreloadViewPager pager;
    /**
     * 消息按钮
     */
    @BindView(R.id.ehome_message)
    RadioButton ehomeMessage;
    /**
     * 主页按钮
     */

    @BindView(R.id.ehome_page)
    RadioButton ehomePage;
    /**
     * 团队按钮
     */
    @BindView(R.id.ehome_team)
    RadioButton ehomeTeam;
    /**
     * 我的页面按钮
     */
    @BindView(R.id.ehome_set)
    RadioButton ehomeSet;

    private List<Fragment> fragmentList = new ArrayList<>();

    CustomFragmentPagerAdapter adapter = null;
    private int currIndex = 0;
    private long mExitTime;
    int camera = 0;
    UserBean userbean;
    String color = "";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        setColor();
        isPressmion();
        onClicks();
        int intents = getIntent().getIntExtra("intent", 0);
        if (intents != 1) {
            if (CommonUtils.isIndex) {
                CheckUpdate();
                CommonUtils.isIndex = false;
            }
        }

        initView();
    }

    /**
     * 设置颜色
     */
    public void setColor() {
        if (SystemConfigFactory.getInstance(MainActivity.this).getSystemConfig().getColor() == null ||
                "".equals(SystemConfigFactory.getInstance(MainActivity.this).getSystemConfig().getColor())) {
            color = "#00a0e9";
            SystemConfigFactory.getInstance(MainActivity.this).getSystemConfig().setColor(color);
        }
        ehomePage.setTextColor(Color.parseColor(SystemConfigFactory.getInstance(MainActivity.this).getSystemConfig().getColor()));
        ehomeSet.setTextColor(Color.parseColor("#999999"));
        ehomeMessage.setTextColor(Color.parseColor("#999999"));
        ehomeTeam.setTextColor(Color.parseColor("#999999"));
        TintManager.setCompoundTint(ehomePage, Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()), false);
        TintManager.setCompoundTint(ehomeMessage, Color.parseColor("#999999"), false);
        TintManager.setCompoundTint(ehomeTeam, Color.parseColor("#999999"), false);
        TintManager.setCompoundTint(ehomeSet, Color.parseColor("#999999"), false);

    }

    /**
     * 点击事件
     */
    public void onClicks() {
        ehomeMessage.setOnCheckedChangeListener(this);
        ehomePage.setOnCheckedChangeListener(this);
        ehomeTeam.setOnCheckedChangeListener(this);
        ehomeSet.setOnCheckedChangeListener(this);
        pager.setOnPageChangeListener(this);
    }

    /**
     * 初始页面
     */
    public void initView() {
        if (NotifationReceiver.notifation == 2) {
            //打开NotificationActivity这个Activity后把通知给关掉
            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            manager.cancel(1);
        }
        String user = SystemConfigFactory.getInstance(MainActivity.this).getSystemConfig().getUserBean();
        userbean = new Gson().fromJson(user, UserBean.class);
        if (userbean != null) {
            if (userbean.getIsManager().equals("1")) {//内勤人员
                ehomePage.setText("学习");
                ehomeTeam.setText("活动");
                initPagers();

            } else {//其他人员
                initPager();
            }
        }
    }

    /**
     * 其他人员加载页面
     */
    public void initPager() {
        fragmentList.add(new MessageFragment());
        fragmentList.add(new PageFragment());
        fragmentList.add(new TeamFragment());
        fragmentList.add(new SetFragment());
        adapter = new CustomFragmentPagerAdapter(getSupportFragmentManager(), fragmentList);
        pager.setAdapter(adapter);
        // 设置默认打开第2页
        pager.setCurrentItem(1);
    }

    /**
     * 内勤人员加载页面
     */
    public void initPagers() {
        fragmentList.add(new MessageFragment());
        fragmentList.add(new StudyFragment());
        fragmentList.add(new HdFragment());
        fragmentList.add(new SetFragment());
        adapter = new CustomFragmentPagerAdapter(getSupportFragmentManager(), fragmentList);
        pager.setAdapter(adapter);
        // 设置默认打开第2页
        pager.setCurrentItem(1);
    }

    /**
     * 检查更新
     */
    public void CheckUpdate() {

        CheckUpdateManger manager = new CheckUpdateManger(MainActivity.this);
        // 检查软件更新
        manager.checkUpdate();

    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        switch (position) {
            case 0:

                if (currIndex == 1) {// 从页卡1跳转转到页卡2
                    ehomeMessage.setChecked(true);
                    ehomePage.setChecked(false);
                    ehomeTeam.setChecked(false);
                    ehomeSet.setChecked(false);
                } else if (currIndex == 2) {// 从页卡1跳转转到页卡3
                    ehomeMessage.setChecked(true);
                    ehomePage.setChecked(false);
                    ehomeTeam.setChecked(false);
                    ehomeSet.setChecked(false);
                } else if (currIndex == 3) {// 从页卡1跳转转到页卡3
                    ehomeMessage.setChecked(true);
                    ehomePage.setChecked(false);
                    ehomeTeam.setChecked(false);
                    ehomeSet.setChecked(false);
                }
                break;
            case 1:
                if (currIndex == 0) {// 从页卡1跳转转到页卡2
                    ehomeMessage.setChecked(false);
                    ehomePage.setChecked(true);
                    ehomeTeam.setChecked(false);
                    ehomeSet.setChecked(false);
                } else if (currIndex == 2) {// 从页卡1跳转转到页卡3
                    ehomeMessage.setChecked(false);
                    ehomePage.setChecked(true);
                    ehomeTeam.setChecked(false);
                    ehomeSet.setChecked(false);
                } else if (currIndex == 3) {// 从页卡1跳转转到页卡3
                    ehomeMessage.setChecked(false);
                    ehomePage.setChecked(true);
                    ehomeTeam.setChecked(false);
                    ehomeSet.setChecked(false);
                }
                break;
            case 2:

                if (currIndex == 0) {// 从页卡1跳转转到页卡2
                    ehomeMessage.setChecked(false);
                    ehomePage.setChecked(false);
                    ehomeTeam.setChecked(true);
                    ehomeSet.setChecked(false);
                } else if (currIndex == 1) {// 从页卡1跳转转到页卡3
                    ehomeMessage.setChecked(false);
                    ehomePage.setChecked(false);
                    ehomeTeam.setChecked(true);
                    ehomeSet.setChecked(false);
                } else if (currIndex == 3) {// 从页卡1跳转转到页卡3
                    ehomeMessage.setChecked(false);
                    ehomePage.setChecked(false);
                    ehomeTeam.setChecked(true);
                    ehomeSet.setChecked(false);
                }
                break;
            case 3:
                if (currIndex == 0) {// 从页卡1跳转转到页卡2
                    ehomeMessage.setChecked(false);
                    ehomePage.setChecked(false);
                    ehomeTeam.setChecked(false);
                    ehomeSet.setChecked(true);
                } else if (currIndex == 1) {// 从页卡1跳转转到页卡3
                    ehomeMessage.setChecked(false);
                    ehomePage.setChecked(false);
                    ehomeTeam.setChecked(false);
                    ehomeSet.setChecked(true);
                } else if (currIndex == 2) {// 从页卡1跳转转到页卡3
                    ehomeMessage.setChecked(false);
                    ehomePage.setChecked(false);
                    ehomeTeam.setChecked(false);
                    ehomeSet.setChecked(true);
                }
                break;
        }
        currIndex = position;
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (ehomeMessage.isChecked()) {
            MobclickAgent.onEvent(this, "xiaoxi");
            TintManager.setCompoundTint(ehomeMessage, Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()), false);
            ehomeMessage.setTextColor(Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));

            TintManager.setCompoundTint(ehomePage, Color.parseColor("#999999"), false);
            TintManager.setCompoundTint(ehomeTeam, Color.parseColor("#999999"), false);
            TintManager.setCompoundTint(ehomeSet, Color.parseColor("#999999"), false);
            ehomeSet.setTextColor(Color.parseColor("#999999"));
            ehomePage.setTextColor(Color.parseColor("#999999"));
            ehomeTeam.setTextColor(Color.parseColor("#999999"));
            pager.setCurrentItem(0);
        } else if (ehomePage.isChecked()) {
            TintManager.setCompoundTint(ehomePage, Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()), false);
            ehomePage.setTextColor(Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));

            TintManager.setCompoundTint(ehomeMessage, Color.parseColor("#999999"), false);
            TintManager.setCompoundTint(ehomeTeam, Color.parseColor("#999999"), false);
            TintManager.setCompoundTint(ehomeSet, Color.parseColor("#999999"), false);
            ehomeSet.setTextColor(Color.parseColor("#999999"));
            ehomeMessage.setTextColor(Color.parseColor("#999999"));
            ehomeTeam.setTextColor(Color.parseColor("#999999"));
            pager.setCurrentItem(1);
        } else if (ehomeTeam.isChecked()) {
            MobclickAgent.onEvent(this, "tuandui");
            TintManager.setCompoundTint(ehomeTeam, Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()), false);
            ehomeTeam.setTextColor(Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));

            TintManager.setCompoundTint(ehomeMessage, Color.parseColor("#999999"), false);
            TintManager.setCompoundTint(ehomePage, Color.parseColor("#999999"), false);
            TintManager.setCompoundTint(ehomeSet, Color.parseColor("#999999"), false);
            ehomeSet.setTextColor(Color.parseColor("#999999"));
            ehomeMessage.setTextColor(Color.parseColor("#999999"));
            ehomePage.setTextColor(Color.parseColor("#999999"));
            pager.setCurrentItem(2);
        } else if (ehomeSet.isChecked()) {
            TintManager.setCompoundTint(ehomeSet, Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()), false);
            ehomeSet.setTextColor(Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));

            TintManager.setCompoundTint(ehomeMessage, Color.parseColor("#999999"), false);
            TintManager.setCompoundTint(ehomeTeam, Color.parseColor("#999999"), false);
            TintManager.setCompoundTint(ehomePage, Color.parseColor("#999999"), false);
            ehomeTeam.setTextColor(Color.parseColor("#999999"));
            ehomeMessage.setTextColor(Color.parseColor("#999999"));
            ehomePage.setTextColor(Color.parseColor("#999999"));
            pager.setCurrentItem(3);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {

                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();
            } else {
                AppManager appManager = AppManager.getAppManager();
                appManager.finishAllActivity();
                finish();
            }

            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 查看是否是6。0以上系统
     */
    public void isPressmion() {
        String[] perms = {android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_PHONE_STATE};
        if (Build.VERSION.SDK_INT >= 23) {
            camera = 1;
            if (EasyPermissions.hasPermissions(this, perms)) {//检查是否获取该权限
                if (App.clientId == null || "".equals(App.clientId)) {
                    OpenGetui();
                }
            } else {
                //第二个参数是被拒绝后再次申请该权限的解释
                //第三个参数是请求码
                //第四个参数是要申请的权限
                EasyPermissions.requestPermissions(this, "为了您能正常使用本应用，请开启手机读写权限！", 0, perms);
            }
        } else {
            if (App.clientId == null || "".equals(App.clientId)) {
                OpenGetui();
            }
            EasyPermissions.requestPermissions(this, "为了您能正常使用本应用，请开启手机读写权限！", 0, perms);
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (camera == 1) {
            if (App.clientId == null || "".equals(App.clientId)) {
                OpenGetui();
            }
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this, "为了您能接收消息通知，请开启手机读写权限！")
                    .setTitle("提示")
                    .setPositiveButton("去设置")
                    .setNegativeButton("取消", null)
                    .setRequestCode(0)
                    .build()
                    .show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /**
     * 初始化个推
     */
    public void OpenGetui() {
        // com.getui.demo.DemoPushService 为第三方自定义推送服务
        PushManager.getInstance().initialize(this.getApplicationContext(), DemoPushService.class);
        PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), DemoIntentService.class);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        App.payloadData.delete(0, App.payloadData.length());
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }
}
